{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\nTrue\n"
     ]
    }
   ],
   "source": [
    "# 问题：我们需要在字符串开头或者结尾处按照指定的文本模式做检查，例如检查文件的扩展名，URL协议类型等。\n",
    "# 解决方案：str.startwith() str.endswith()\n",
    "\n",
    "filename = 'spam.txt'\n",
    "print(filename.endswith('.txt'))\n",
    "\n",
    "url = 'http://www.python.org'\n",
    "print(url.startswith('http:'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "# 如果需要同时针对多个选项做检查，只需要startwith() 和  endswith() 提供包含可能选项的元组即可。\n",
    "filenames = ['Makefile', 'foo.c', 'bar.py','spam.c', 'spam.h' ]\n",
    "cfile = [name for name in filenames if name.endswith(('.c', '.h'))]\n",
    "# print(cfile)\n",
    "\n",
    "# any() 函数用于判断给定的可迭代参数 iterable 是否全部为空对象，\n",
    "# 如果都为空、0、false，则返回 False，如果不都为空、0、false，则返回 True。\n",
    "print(any(name.endswith('.py') for name in filenames))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from urllib.request import urlopen\n",
    "\n",
    "\n",
    "def read_data(name):\n",
    "    if name.startwith(('http:', 'https:', 'ftp:')):\n",
    "        return urlopen(name).read()\n",
    "    else:\n",
    "        with open(name) as f:\n",
    "            return f.read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "# 使用startwith endswith 时，确保传入的是元组，而不是列表或者集合。\n",
    "\n",
    "choices = ['http:', 'ftp:']\n",
    "url = 'http://www.python.org'\n",
    "print(url.startswith(tuple(choices)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    ""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2.0
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}